<?php
/* 
 * class.core.php
 * 系统核心类：处理核心事件（DB,TPL,SESSION），初始化系统，驱动系统
 * 文件版本 V1.0
 * @author samuel
 * @date 2009-05-04
 */

class Core {

    private $version;

    public static $instance = null;
    public static $eModules = array();
    
    public $db;
    public $session;
    public $tpl;
    public $params;
    public $utility;

    private function  __construct() {
        $this->version = "0.1";
        
        $this->_check_module();
        $this->_load();
        $this->get_query_params();
    }

    function  __destruct() {
        unset($this);
    }

    //加载Session模块，如果存在
    private function  _load_session(){
        //echo "load_session";return;
        if(!extension_loaded('session')){
            echo "SESSION没有开启，无法加载！";
            return false;
        }

        @ini_set('session.cache_expire',  180);
        @ini_set('session.use_trans_sid', 0);
        @ini_set('session.use_cookies',   1);
        @ini_set('session.auto_start',    0);

        session_start();

        //$this->session = &$_SESSION;

    }
    
    //加载DB模块，如果存在
    private function  _load_db(){
        //echo "load_db";return;
        $db_path = CLASS_PATH . "db/class.db.php";
        if(!file_exists($db_path)){
            echo "数据模块不存在，无法加载！";
            return false;
        }
        include_once($db_path);

        $db = new db($GLOBALS['_CFG']['db_user'], $GLOBALS['_CFG']['db_password'], $GLOBALS['_CFG']['db_name'], $GLOBALS['_CFG']['db_host']);

        $this->db = $db;
        if($GLOBALS['_CFG']['db_charset']) $db->query("SET NAMES " . $GLOBALS['_CFG']['db_charset']);
        
        return $db;
    }

    //加载Smarty模块，如果存在
    private function  _load_smarty(){
        //echo "load_smarty";return;
        $smarty_path = CLASS_PATH . "smarty/Smarty.class.php";
        if(!file_exists($smarty_path)){
            echo "Smarty模块不存在，无法加载！";
            return false;
        }

        include_once($smarty_path);
        
        $smarty = new Smarty();
        $smarty->template_dir = $GLOBALS['_CFG']['smarty_template_dir']; //设置模板目录
        $smarty->compile_dir = $GLOBALS['_CFG']['smarty_compile_dir']; //设置编译目录
        $smarty->cache_dir = $GLOBALS['_CFG']['smarty_cache_dir']; //设置缓存目录
        $smarty->cache_lifetime = $GLOBALS['_CFG']['smarty_cache_lifetime']; //设置缓存时间
        $smarty->caching = $GLOBALS['_CFG']['smarty_cache'];
        $smarty->left_delimiter = $GLOBALS['_CFG']['smarty_left_delimiter']; //设置左边界符
        $smarty->right_delimiter = $GLOBALS['_CFG']['smarty_right_delimiter']; //设置右边界符

        //变量预处理
        $smarty->assign('CURRENT_THEME_URL', THEME_URL . $GLOBALS['_CFG']['theme'] );
        $smarty->assign('IMAGE_URL', IMAGE_URL );

        $this->tpl = $smarty;

        return $smarty;
    }

    //加载Cache模块，如果存在
    private function  _load_cache(){
       // echo "load_cache";return;
    }

    //加载Log模块，如果存在
    private function _load_log(){
        
    }

    //加载工具类
    private function _load_utility(){
        $utility_path = CLASS_PATH . "class.utility.php";
        if(!file_exists($utility_path)){
            echo "公共函数库不存在，无法加载！";
            return false;
        }
        include_once($utility_path);

        $utility = new utility($this);

        $this->utility = $utility;

        return $utility;
    }

    //检测系统必要模块，如果不存在则报错
    private function  _check_module(){
        return true;
    }

    //自动检测模块，如果存在则自动加载
    private function _load(){
        $arr_load = array();//需要自动加载的函数
        $arr_methods = get_class_methods($this);
        if(!empty ($arr_methods)){
            foreach($arr_methods as $method){
                if(preg_match("/^_load_.*/", $method)) $arr_load[] = $method;
            }
        }
        //自动加载以_load开头的方法
        if(!empty($arr_load)){
            foreach($arr_load as $method){
                $this->$method();
            }
        }
    }

    //请求参数处理
    public function  get_query_params(){
		//处理地址栏传递的参数
        $query = $_SERVER['QUERY_STRING'];
        $arr_params = array();
        parse_str($query, &$arr_params);

        //处理通过表单POST过来的参数
        if($_POST){
            foreach($_POST as $key => $value){
                if(!is_array($value)){
                    $arr_params[$key] = mysql_escape_string(trim($value));
                }else{
                    $arr_params[$key] = $value;
                }
            }
        }

        //处理$_FILE参数

        $this->params = $arr_params;
        
        return $arr_params;
    }

    //系统初始化调度
    public static function  init(){
        if(!isset(self::$instance)){
            self::$instance = new Core();
        }
        return self::$instance;
    }

    //加载外部模块
    public function load($module, $param="", $static=""){
        if(!$module) return false;

		$t_module = $classname = $namespace = $module_path1 = $module_path2 = $arr_path = null;
		if(strpos($module, '::') !== false){//使用命名空间
			$arr_path = @explode('::', $module);
			$t_module = str_replace('::', '_', $module);
			$classname = $arr_path[1];
			$namespace = true;
		}else{
			$t_module = $classname =  $module;
			$namespace = false;
		}

        if(!isset(self::$eModules[$t_module])){
			if($namespace){
				$module_path1 = CLASS_PATH . "{$arr_path[0]}/" . "class.{$arr_path[1]}.php";
				$module_path2 = MODULE_PATH . "{$arr_path[0]}/" . "class.{$arr_path[1]}.php";
			}else{
				$module_path1 = CLASS_PATH . "{$module}/" . "class.{$module}.php";
				$module_path2 = MODULE_PATH . "{$module}/" . "class.{$module}.php";
			}
            
            if(file_exists($module_path1)){
				include_once $module_path1;
			}elseif(file_exists($module_path2)){
				include_once $module_path2;
			}else{
				die('无法加载模块！');
			}
			
            if($static){
                $eval_str = 'self::$eModules[' . $t_module . '] = ' . $classname . '::' . $static . '(' . $param . ' );';
                eval($eval_str);
            }else{
                self::$eModules[$t_module] = new $classname( $param );
            }
        }
        return self::$eModules[$t_module];
    }

    //驱动系统
    public function  run(){
        //获取模块动作
        $module = $this->params['module'] ? strtolower(trim( $this->params['module'] )) : 'default';
        $act = $this->params['act'] ? strtolower( trim( $this->params['act'] ) ) : 'index';

		//判断用户的登录状态，登录页面不需要判断
        $loginTag = $this->utility->checkLoginStatus();
		if(!$loginTag && !in_array($module . '::' . $act, $GLOBALS['_CFG']['no_auth_module'])){//未登录且需要验证
			//session_unset();
			$login_url = ROOT_URL . "index.php?module=admin&act=login";
            header('Location: ' . $login_url);
            return;
		}

        $module_path = MODULE_PATH . "{$module}/" . "class.$act.php";
        if(!file_exists( $module_path )) die('无法加载动作模块，请检查！');
        include_once $module_path;
        $classname = $module . "_" . $act;
        $app = new $classname($this);
    }
    
    //驱动WAP页面
    public function runWap(){
    	//获取一级模块
    	$module = $this->params['module'] ? strtolower(trim($this->params['module'])) : basename($_SERVER['PHP_SELF'], '.php');
    	//获取二级模块
    	$act = $this->params['act'] ? strtolower(trim($this->params['act'])) : 'index';
    	
    	$module_path = MODULE_PATH . "{$module}/" . "class.$act.php";
        if(!file_exists( $module_path )) die('无法加载动作模块，请检查！');
        include_once $module_path;
        $classname = $module . "_" . $act;
        $app = new $classname($this);
    }
    
}

//自动加载函数
//function __autoload( $classname ){
//    $arr = @explode('_', $classname);
//    $module = $arr[0];
//    $act = $arr[1];
//    $module_path = MODULE_PATH . "{$module}/" . "class.$act.php";
//    if(!file_exists( $module_path )) die('无法加载动作模块，请检查！');
//    include_once $module_path;
//}

?>
